package com.cardone.common.action;

import java.lang.reflect.InvocationTargetException;
import java.util.Map;
import java.util.Map.Entry;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;

import com.cardone.context.action.Run3Action;

/**
 * bean属性名称支持
 *
 * @author fand.cardone
 *
 */
@Slf4j
public class CopyPropertiesBean2BeanForNameAction implements Run3Action<Object, Object, Map<String, Object>> {
	@Override
	public void run(final Object source, final Object target, final Map<String, Object> parameters) {
		if (source == null) {
			return;
		}

		if (target == null) {
			return;
		}

		if (MapUtils.isEmpty(parameters)) {
			return;
		}

		for (final Entry<String, Object> parameterEntry : parameters.entrySet()) {
			try {
				final Object value = PropertyUtils.getProperty(source, parameterEntry.getKey());

				String targetName = null;

				if (parameterEntry.getValue() instanceof String) {
					targetName = (String) parameterEntry.getValue();
				}

				if (StringUtils.isBlank(targetName)) {
					targetName = parameterEntry.getKey();
				}

				PropertyUtils.setProperty(target, targetName, value);
			} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
				CopyPropertiesBean2BeanForNameAction.log.error(e.getMessage(), e);
			}
		}
	}
}
